package com.yutian.selfservice.support.upload.handler.storage;


import com.yutian.selfservice.support.upload.config.UploadConfig;
import com.yutian.selfservice.support.upload.handler.UploadResult;
import com.yutian.selfservice.support.utils.Result;
import com.yutian.selfservice.support.utils.SnowflakeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 上传至本地
 */
@Slf4j
@Component("local")
public class LocalStorage implements Storage {


    @Override
    public Result storage(MultipartFile multipartFile, UploadConfig.UploadProperties uploadProperties) {
        try {
            Long id = SnowflakeUtils.nextId();
            String fileName = id + "." + FilenameUtils.getExtension(multipartFile.getName());
            File file = new File(uploadProperties.getRootPath() + File.separator, fileName);
            FileUtils.createParentDirectories(file);
            multipartFile.transferTo(file);
            String remoteUrl=uploadProperties.getAccessUrl() + File.separator + fileName;
            return Result.success(UploadResult.builder().id(id).fileName(multipartFile.getName()).remoteUrl(remoteUrl).build());
        } catch (IOException e) {
            log.error("本地文件上传异常", e);
            return Result.fail("上传异常");
        }
    }
}
